using System.Security.Claims;
using Identity.Application.Users.Commands;
using MediatR;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;

[ApiController]
public class AuthorizationController : ControllerBase
{
    private readonly IMediator _mediator;

    public AuthorizationController(IMediator mediator)
    {
        _mediator = mediator;
    }

    
    [HttpGet("~/connect/authorize")]
    public async Task<IActionResult> Authorize()
    {
        var request = HttpContext.GetOpenIddictServerRequest()
                      ?? throw new InvalidOperationException();

        // 从 Query 或 Header 中获取临时登录凭证
        string tempToken = Request.Query["temp_token"]!;
        if (string.IsNullOrEmpty(tempToken))
        {
            tempToken = Request.Headers["X-Temp-Token"]!;
        }

        if (string.IsNullOrEmpty(tempToken))
        {
            return Unauthorized(new { error = "missing_temp_token" });
        }

        var command = new AuthorizeCommand(tempToken);
        var tempClaims = await _mediator.Send(command);

        var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

        foreach (var claim in tempClaims)
        {
            if (claim.Type == "sub") identity.AddClaim(new Claim(Claims.Subject, claim.Value!)
                                             .SetDestinations(Destinations.AccessToken, Destinations.IdentityToken));

            else if (claim.Type == "name") identity.AddClaim(new Claim(Claims.Name, claim.Value!)
                                             .SetDestinations(Destinations.AccessToken));
            else if (claim.Type == "role") identity.AddClaim(new Claim(Claims.Role, claim.Value!)
                                             .SetDestinations(Destinations.AccessToken));
            else identity.AddClaim(new Claim(claim.Type, claim.Value!)
                         .SetDestinations(Destinations.AccessToken));
        }

        var principal = new ClaimsPrincipal(identity);
        // 设置授权范围与 token 生命周期
        principal.SetScopes(request.GetScopes());
        principal.SetResources("api");
        principal.SetAccessTokenLifetime(TimeSpan.FromMinutes(60));
        principal.SetRefreshTokenLifetime(TimeSpan.FromDays(14));

        // 返回授权成功
        return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
    }

}
